package com.yaodian100.mall.payment;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.payment.service.ThirdpartyPaymentService;
import com.yaodian100.mall.member.util.UserData;

public class PaymentAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4768292672127661372L;

	private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(PaymentAction.class);

	private Long totalAmount;// 付款總額
	private String orderId;// 訂單編號
	private String paymentType;// 付款方式
	private String fixString;// 字串
	private String key;
	private String bankCode;
	private String period;

	@Resource
	private ThirdpartyPaymentService thirdpartyPaymentService;
	@Resource
	private MemberService memberService;

	// public String payment() {
	//
	// HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
	// ServletActionContext.HTTP_RESPONSE);
	// HttpServletRequest request = (HttpServletRequest)
	// ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
	//
	//
	// }

	public String alipay() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		request.setAttribute("payment", "alipayR");

		// 支付寶快捷登入會員在簽名時要加入token參數
		UserData userData = new UserData(request, response);
		String token = StringUtils.defaultString(userData.readRawValue(UserData.NAME_YAODIAN100_ALIPAY_TOKEN));

		Calendar in30mins = Calendar.getInstance();
		in30mins.add(Calendar.MINUTE, -30);

		Calendar lastLogin = Calendar.getInstance();
		if (null != memberService.getLastLoginHistory(userData.getLoginId())) {
			lastLogin.setTime(memberService.getLastLoginHistory(userData.getLoginId()).getLoginTime());
			if (lastLogin.compareTo(in30mins) < 0) {// token超過30分鐘無效
				token = "";
			}
		}

		Map<String, String> params;
		if (StringUtils.isNotBlank(bankCode)) {
			params = thirdpartyPaymentService.alipaySend(orderId, paymentType, bankCode, token);
		} else {
			params = thirdpartyPaymentService.alipaySend(orderId, paymentType, "", token);
		}

		request.setAttribute("params", params);
		request.setAttribute("actionURL", "https://www.alipay.com/cooperate/gateway.do?_input_charset=utf-8");

		return "alipay";
	}

	public String alipayNotify() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		Map<String, String> params = pharseParams(request.getParameterMap());
		boolean isSuccess = thirdpartyPaymentService.alipayNotify(params);
		if (isSuccess) {
			request.setAttribute("titleMsg", "支付宝");
			request.setAttribute("headerMsg", "");
			request.setAttribute("bodyMsg", "success");

			request.setAttribute("alipay", "Y");
			return "notify";
		} else {
			return "fail";
		}

	}

	public String alipayDanbaoNotify() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		Map<String, String> params = pharseParams(request.getParameterMap());
		params.put("danbao", "Y");
		boolean isSuccess = thirdpartyPaymentService.alipayNotify(params);
		if (isSuccess) {
			request.setAttribute("titleMsg", "支付宝");
			request.setAttribute("headerMsg", "");
			request.setAttribute("bodyMsg", "success");

			request.setAttribute("alipay", "Y");

			return "notify";
		} else {
			return "fail";
		}

	}

	public String alipayReturn() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		Map<String, String> params = pharseParams(request.getParameterMap());

		boolean isSuccess = thirdpartyPaymentService.alipayReturn(params);
		if (isSuccess) {
			setOrderId(params.get("out_trade_no"));
			return "return";
		} else {
			return "fail";
		}

	}

	public String alipayDanbaoReturn() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		Map<String, String> params = pharseParams(request.getParameterMap());
		params.put("danbao", "Y");
		boolean isSuccess = thirdpartyPaymentService.alipayReturn(params);
		if (isSuccess) {
			setOrderId(params.get("out_trade_no"));
			return "return";
		} else {
			return "fail";
		}

	}

	public String tenpay() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		String userIP = request.getHeader("X-Forwarded-For");
		if (StringUtils.isBlank(userIP)) {
			userIP = request.getRemoteAddr();
		}

		Map<String, String> params = thirdpartyPaymentService.tenpaySend(orderId, userIP);

		request.setAttribute("params", params);
		request.setAttribute("actionURL",
				"https://www.tenpay.com/cgi-bin/v1.0/pay_gate.cgi?desc=%D2%AB%B5%E3100%C9%CC%C6%B7");

		return "tenpay";
	}

	public String tenpayNotify() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		Map<String, String> params = pharseParams(request.getParameterMap());

		boolean isSuccess = thirdpartyPaymentService.tenpayReturn(params);
		if (isSuccess) {
			request.setAttribute("titleMsg", "财付通");
			request.setAttribute("headerMsg", "<meta name=\"TENCENT_ONLINE_PAYMENT\" content=\"China TENCENT\">");
			request.setAttribute("bodyMsg", "<script>location.replace('" + ServerValue.getFrontContextPath()
					+ "/shopping/paymentInfo/paymentInfoView.do?orderId=" + params.get("sp_billno") + "')</script>");
			// setOrderId(params.get("sp_billno"));
			return "notify";
		} else {
			return "fail";
		}
	}

	// public String tenpayReturn() {
	// HttpServletRequest request = (HttpServletRequest)
	// ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
	//
	// Map<String, String> params = pharseParams(request.getParameterMap());
	//
	// boolean isSuccess = thirdpartyPaymentService.tenpayReturn(params);
	// if (isSuccess) {
	// setOrderId(params.get("sp_billno"));
	// return "return";
	// } else {
	// return "fail";
	// }
	// }

	public String chinapay() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		Map<String, String> params = thirdpartyPaymentService.chinapaySend(orderId);

		request.setAttribute("params", params);
		// request.setAttribute("actionURL", "http://payment-test.chinapay.com/pay/TransGet");//測試環境
		request.setAttribute("actionURL", "https://payment.chinapay.com/pay/TransGet");// 正式環境

		return "chinapay";
	}

	public String chinapayNotify() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		Map<String, String> params = pharseParams(request.getParameterMap());

		boolean isSuccess = thirdpartyPaymentService.chinapayReturn(params);
		if (isSuccess) {
			request.setAttribute("titleMsg", "银联");
			request.setAttribute("headerMsg", "");
			request.setAttribute("bodyMsg", "success");
			return "notify";
		} else {
			return "fail";
		}
	}

	public String chinapayReturn() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		Map<String, String> params = pharseParams(request.getParameterMap());

		boolean isSuccess = thirdpartyPaymentService.chinapayReturn(params);
		if (isSuccess) {
			String tid = params.get("orderno");
			String thisYear = new SimpleDateFormat("yy").format(new Date());

			setOrderId(thisYear + tid.substring(0, 4) + tid.substring(9));
			return "return";
		} else {
			return "fail";
		}
	}

	public String quickmoney() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		Map<String, String> params = thirdpartyPaymentService.quickmoneySend(orderId, bankCode);

		request.setAttribute("params", params);
		// request.setAttribute("actionURL", "https://sandbox.99bill.com/gateway/recvMerchantInfoAction.htm");//測試環境
		request.setAttribute("actionURL", "https://www.99bill.com/gateway/recvMerchantInfoAction.htm");// 正式環境

		return "quickMoney";
	}

	// 快錢CreditCard
	public String quickmoneyCC() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		if ("1".equals(period)
				|| (!"1".equals(period) && thirdpartyPaymentService.isVaildCreditCardSendInfo(orderId, period, ""))) {
			Map<String, String> params = thirdpartyPaymentService.quickmoneyCreditCardSend(orderId, period, "");// bankCode目前用不到

			request.setAttribute("params", params);
			// request.setAttribute("actionURL", "https://sandbox.99bill.com/gateway/recvMerchantInfoAction.htm");// 測試環境
			request.setAttribute("actionURL", "https://www.99bill.com/gateway/recvMerchantInfoAction.htm");// 正式環境
			return "quickMoney";
		} else {
			setOrderId(orderId);
			this.addActionError("付款参数不合法");
			return "return";
		}

	}

	public String quickmoneyNotify() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		Map<String, String> params = pharseParams(request.getParameterMap());
		boolean isSuccess = false;
		if (params.containsKey("payType")) {
			if ("15".equals(params.get("payType"))) {// 信用卡
				isSuccess = thirdpartyPaymentService.quickmoneyCreditCardNotify(params);
			} else {
				isSuccess = thirdpartyPaymentService.quickmoneyNotify(params);
			}
		}
		if (isSuccess) {
			request.setAttribute("titleMsg", "快钱");
			request.setAttribute("headerMsg", "");
			request.setAttribute("bodyMsg", "<result>1</result><redirecturl>" + ServerValue.getFrontHostname()
					+ "</redirecturl> ");
			request.setAttribute("quickMoney", "Y");
			return "notify";
		} else {
			return "fail";
		}

	}

	public String quickmoneyReturn() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		Map<String, String> params = pharseParams(request.getParameterMap());

		boolean isSuccess = false;
		if (params.containsKey("payType")) {
			if ("15".equals(params.get("payType"))) {// 信用卡
				isSuccess = thirdpartyPaymentService.quickmoneyCreditCardReturn(params);
			} else {
				isSuccess = thirdpartyPaymentService.quickmoneyReturn(params);
			}
		}

		if (isSuccess) {
			setOrderId(params.get("orderId"));
			return "return";
		} else {
			return "fail";
		}
	}

	private Map<String, String> pharseParams(Map<String, String[]> params) {
		Map<String, String> map = new HashMap<String, String>();
		Set<String> key = params.keySet();
		for (Iterator<String> it = key.iterator(); it.hasNext();) {
			String name = it.next();
			String[] value = params.get(name);
			map.put(name, value[0]);

		}
		return map;
	}

	/**
	 * @return the totalAmount
	 */
	public Long getTotalAmount() {
		return totalAmount;
	}

	/**
	 * @param totalAmount the totalAmount to set
	 */
	public void setTotalAmount(Long totalAmount) {
		this.totalAmount = totalAmount;
	}

	/**
	 * @return the orderId
	 */
	public String getOrderId() {
		return orderId;
	}

	/**
	 * @param orderId the orderId to set
	 */
	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	/**
	 * @return the paymentType
	 */
	public String getPaymentType() {
		return paymentType;
	}

	/**
	 * @param paymentType the paymentType to set
	 */
	public void setPaymentType(String paymentType) {
		this.paymentType = paymentType;
	}

	/**
	 * @return the fixString
	 */
	public String getFixString() {
		return fixString;
	}

	/**
	 * @param fixString the fixString to set
	 */
	public void setFixString(String fixString) {
		this.fixString = fixString;
	}

	/**
	 * @return the key
	 */
	public String getKey() {
		return key;
	}

	/**
	 * @param key the key to set
	 */
	public void setKey(String key) {
		this.key = key;
	}

	/**
	 * @return the bankCode
	 */
	public String getBankCode() {
		return bankCode;
	}

	/**
	 * @param bankCode the bankCode to set
	 */
	public void setBankCode(String bankCode) {
		this.bankCode = bankCode;
	}

	/**
	 * @return the period
	 */
	public String getPeriod() {
		return period;
	}

	/**
	 * @param period the period to set
	 */
	public void setPeriod(String period) {
		this.period = period;
	}

}
